package cj.web.vote.controllers;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import com.alibaba.fastjson.JSON;

import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.web.utils.HttpClientUtil;
import cj.web.utils.NetworkUtil;
import cj.web.utils.StandardResponse;
import cj.web.vote.dao.SongDAO;
import cj.web.vote.dao.VoteDAO;
import cj.web.vote.dao.VoteLogDAO;
import cj.web.vote.dao.VoteSongRefDAO;
import cj.web.vote.domain.Song;
import cj.web.vote.domain.Vote;
import cj.web.vote.domain.VoteLog;

@Path("/vote")
public class VoteController {
	
	public static String charset = "utf-8";  
	
	public static final int bestVoice = 1;
	//上榜歌曲
	public static final String BESTVOICE_VOTE_TYPE_LIST_SONG = "1";
	//打榜歌曲
	public static final String BESTVOICE_VOTE_TYPE_HIT_SONG = "2";
	
	@Autowired
	VoteDAO voteDAO;
	@Autowired
	VoteLogDAO voteLogDAO;
	@Autowired
	SongDAO songDAO;
	@Autowired
	VoteSongRefDAO voteSongRefDAO;
	
	/**
	 * 获取现在有效的投票
	 * @return
	 */
	@Get("list")
	public String list(Model model,@Param("code") String code,@Param("openid") String openid,HttpServletRequest request){
		try {
			openid = NetworkUtil.getIpAddress(request);
		} catch (IOException e1) {
			UUID uuid = UUID.randomUUID();
			openid = uuid.toString();
		}
//		openid = "ofwuNswvO5usQiL5qfjIowAVykOU";
		//放入投票
		String nowdate = DateUtils.getNowTime();//当前时间
		Vote btVote = voteDAO.queryNowVote(nowdate);
		if(null != btVote){
			int voteId = btVote.getId();
			model.add("vote",btVote);
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd");
			model.add("start",sdf.format(btVote.getStartDate()));
			model.add("end",sdf.format(btVote.getEndDate()));
			//上榜歌曲
			List<Map> listSongs = voteDAO.querySongListFromVote(String.valueOf(btVote.getId()),BESTVOICE_VOTE_TYPE_LIST_SONG,10);
			model.add("listSongs",listSongs);
			//打榜歌曲
			List<Map> hitSongs = voteDAO.querySongListFromVote(String.valueOf(btVote.getId()),BESTVOICE_VOTE_TYPE_HIT_SONG,3);
			model.add("hitSongs",hitSongs);
			boolean voteBefore = false;
			
			//======================================下面是微信登陆========================================================
			if(null == openid ||"".equals(openid)){
				try{
					String step2BodyJson = HttpClientUtil.get("https://api.weixin.qq.com/sns/oauth2/access_token?"
							+ "appid="+Constants.weixinkey.AppID
							+ "&secret="+Constants.weixinkey.AppSecret
							+ "&code="+code
							+ "&grant_type=authorization_code");
					JSONObject jsobj =new JSONObject().fromObject(step2BodyJson);
					String wx_access_token=jsobj.getString("access_token");
					String wx_openid=jsobj.getString("openid");
					//Step3
					String bodyJson =HttpClientUtil.get("https://api.weixin.qq.com/sns/userinfo?"
							+ "access_token="+wx_access_token
							+ "&openid="+wx_openid);
					JSONObject jsUserObj =new JSONObject().fromObject(bodyJson);
					String wx_openId = jsUserObj.getString("openid");
					if(null != wx_openId && !"".equals(wx_openId)){
						VoteLog voteLog =  voteLogDAO.queryByOpenIdAndVoteId(wx_openId, voteId);
						if(null == voteLog){
							//没有注册,保存对象
							voteLog = new VoteLog();
							voteLog.setWxOpenid(wx_openId);
							voteLog.setWxCity(jsUserObj.get("city").toString());
							voteLog.setWxCountry(jsUserObj.get("country").toString());
							voteLog.setWxHeadimgurl(jsUserObj.get("headimgurl").toString());
							voteLog.setWxNickname(jsUserObj.get("nickname").toString());
							voteLog.setWxProvince(jsUserObj.get("province").toString());
							voteLog.setWxSex(jsUserObj.get("sex").toString());
							voteLog.setWxUnionid(jsUserObj.get("unionid").toString());
							voteLog.setCreateAT(new Date());
							voteLog.setUpdateAT(new Date());
							voteLog.setVoteId(btVote.getId());
							voteLogDAO.create(voteLog);
							int id = voteLogDAO.queryMaxId();
							voteLog.setId(id);
						}else{
							//已经注册,判断是否投过票了
							Integer voteSongId = voteLog.getVoteSongId();
							if(null != voteSongId){
								//已经投过票了
								voteBefore = true;
							}
						}
						//添加投票人信息
						model.add("voteLog",voteLog);
					}else{
						return "@"+ JSON.toJSONString(StandardResponse.response(StandardResponse.ResponseCode.BT_WECHAT_LOGIN_ERROR, null));
					}
				}catch(Exception e){
					return "@"+ JSON.toJSONString(StandardResponse.response(StandardResponse.ResponseCode.BT_WECHAT_LOGIN_ERROR, null));
				}
			}else{
				model.add("openid",openid);
				//======================================下面是网页登陆========================================================
				VoteLog voteLog =  voteLogDAO.queryByOpenIdAndVoteId(openid, voteId);
				if(null == voteLog){
					//没有注册
					voteLog = new VoteLog();
					voteLog.setWxOpenid(openid);
					voteLog.setVoteId(btVote.getId());
					voteLog.setCreateAT(new Date());
					voteLog.setUpdateAT(new Date());
					voteLogDAO.create(voteLog);
					int btVoterid = voteLogDAO.queryMaxId();
					voteLog.setId(btVoterid);
				}else{
					//已经注册,判断是否投过票了
					Integer voteSongId = voteLog.getVoteSongId();
					if(null != voteSongId){
						//已经投过票了
						voteBefore = true;
					}
				}
				//添加投票人信息
				model.add("voteLog",voteLog);
			}
			//是否已经投票
			model.add("voteBefore",voteBefore);
			return "/views/bestvoice/voiceList.vm";
		}else{
			model.add("response",StandardResponse.ResponseCode.BT_NOT_ADD_VOTE.getData());
			return "/views/bestvoice/voiceFinish.vm";
		}
	}
	
	/**
	 * 投票
	 * @param voteId		投票ID
	 * @param voterId		投票人ID
	 * @param voteSongId	歌曲ID
	 * @return
	 */
	@Get("vote")
	public String vote(@Param(value = "voteLogId")int voteLogId,@Param("voteSongId")int voteSongId){
		if(0== voteLogId || 0 == voteSongId){
			return "@"+JSON.toJSONString(StandardResponse.response(StandardResponse.ResponseCode.BT_PARAM_ERROR, null));
		}
		VoteLog voteLog = voteLogDAO.queryById(voteLogId);
		if(null != voteLog.getVoteSongId()){
			return "@"+JSON.toJSONString(StandardResponse.response(StandardResponse.ResponseCode.BT_VOTE_BEFORE, "voteBefore"));
		}else{
			voteLogDAO.update(voteSongId,new Date(),voteLogId);
			return "@"+JSON.toJSONString(StandardResponse.response(StandardResponse.ResponseCode.SUCCESS, null));
		}
	}
	
	/**
	 * 详情
	 * @param voteId		投票ID
	 * @param voterId		投票人ID
	 * @param voteSongId	歌曲ID
	 * @return
	 */
	@Get("detail")
	public String detail(Model model,@Param("openid")String openid,@Param("voteLogId")int voteLogId,
			@Param("voteSongId")int voteSongId,@Param("count")int count,@Param("voteNum")int voteNum){
		model.add("count",count);
		model.add("opneid",openid);
		model.add("voteNum",voteNum);
		model.add("voteSongId",voteSongId);
		//已经注册,判断是否投过票了
		VoteLog voteLog =  voteLogDAO.queryById(voteLogId);
		if(null != voteLog.getVoteSongId()){
			model.add("voteBefore","1");
		}else{
			model.add("voteBefore","0");
		}
		model.add("voteLog",voteLog);
		Song song = songDAO.queryByVoteSongId(voteSongId);
		model.add("song",song);
		return "/views/bestvoice/voiceDetail.vm";
	}
}